<template>
  <div class="tw-libtagfilter">
    <div class="tw-libbirtreport">
      <div v-if="cataData && cataData.length > 0">
        <div class="tw-filterpane" style="margin-bottom: -28px;">
          <div class="tw-tagfilter" :class="{ xopen: opens || !isFolds }">
            <label class="tw-tagfilter-label" :style="{ width: labelWidth }">指标名称:</label>
            <div ref="tag-boxs" class="tw-tagfilter-tags">
              <a
                class="tw-tag xfilter"
                :class="{ xactive: chooseReport === item.reportId || cataData.length === 1 }"
                v-for="(item, index) in cataData"
                :key="index"
                @click="chooseCataId(item, index)"
              >
                <span>{{ item.indicatorName }}</span>
              </a>
              <a
                v-if="isFolds && showToggleBtns"
                class="tw-ico xtftoggle"
                :class="{
                xopen: opens
              }"
                @click="opens = !opens"
              ></a>
            </div>
          </div>
        </div>
        <div class="tw-filterpane" style="margin-bottom: -28px;">
          <div class="tw-tagfilter">
            <label class="tw-tagfilter-label" :style="{ width: labelWidth }">统计年份:</label>
            <div ref="tag-boxs" class="tw-tagfilter-tags">
              <a
                class="tw-tag xfilter"
                :class="{ xactive: chooseReport === item.reportId || cataData.length === 1 }"
                v-for="(item, index) in cataData"
                :key="index"
                @click="chooseCataId(item, index)">
                <span>{{ item.indicatorName }}</span>
              </a>
            </div>
          </div>
        </div>
        <!-- <div class="tw-filterpane">
          <div
            class="tw-tagfilter"
            v-for="(parameter, index) in parameters"
            :key="index"
            :class="{ xopen: open || !isFold }"
          >
            <label
              v-if="parameter.label"
              class="tw-tagfilter-label"
              :style="{ width: labelWidth }"
            >{{ parameter.label }}:</label>
            <div ref="tag-box" class="tw-tagfilter-tags">
              <a
                v-show="tag[dataMap.text] !==''"
                class="tw-tag xfilter"
                :class="{ xactive: defaultValues[index]===tag.value || values[index] === tag.value }"
                v-for="tag in parameter.items"
                :key="tag.value"
                @click="clickTag(tag, index)">
                <span>{{ tag[dataMap.text] }}</span>
              </a>
              <a
                v-if="isFold && showToggleBtn[index]"
                class="tw-ico xtftoggle"
                :class="{
                xopen: open
              }"
                @click="dialogVisible = true; chooseLabel = parameter.label; chooseList = parameter.items; diolagList= parameter.items; ind = index"
              ></a>
            </div>
          </div>
          <div class="tw-filterpane-toolbar">
            <a class="tw-btn xmain" @click="renderReport">查询</a>
            <a class="tw-btn xweaking" @click="renderReset">重置</a>
          </div>
        </div> -->
      </div>
      <div class="tw-libcard xradius" v-if="reportData !== ''">
        <div class="tw-libtitle xnoborder">
          <h3 class="tw-libtitle-left">报表</h3>
          <div class="tw-libtitle-right">
            <a class="tw-libbtn xmain" @click="exportExcel">导出</a>
          </div>
        </div>
        <div class="tw-libbirt-report" v-html="reportData"></div>
      </div>
      <div v-else class="tw-libnodata">
        <img src="./images/nodata.png" />
        <div>暂无数据</div>
      </div>
    </div>

    <!-- 数据量大时以弹窗展示 -->
    <el-dialog
      :title="'更多' + chooseLabel"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <div class="dialog-class">
        <el-input v-model="searchInput" placeholder="请输入内容" style></el-input>
        <a class="tw-btn xmain" @click="tosearchDia()">查询</a>
        <a class="tw-btn xweaking" @click="searchInput = ''; chooseList = diolagList">重置</a>
      </div>
      <div style="height: 300px; overflow-y: auto;margin-top: 10px;">
        <span
          class="tw-tag xfilter"
          :class="{ xactive: values[ind] === tag.value }"
          v-for="tag in chooseList"
          :key="tag.value"
          @click="clickTag(tag, ind)"
        >{{tag[dataMap.text]}}</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- /数据量大时以弹窗展示 -->
  </div>
</template>

<script>
import props from './props'

export default {
  name: 'cs-birt-report',

  props,
  model: {
    prop: 'value',
    event: 'change'
  },
  data () {
    return {
      years: [],
      searchInput: '',
      dialogVisible: false,
      chooseLabel: '',
      ind: '',
      chooseList: [],
      diolagList: [],
      dataMap: {
        text: 'label',
        value: 'value'
      },
      chooseReport: '', // 选中的指标
      values: [], // 选中的数组
      defaultValues: [],
      open: false,
      opens: false,
      showToggleBtn: [],
      showToggleBtns: false,
      isFolds: true, // 是否需要收起展开
      isFold: true, // 是否需要收起展开
      toggleHeight: 50,
      reportData: '',
      birtValue: '',
      parameters: [], // 菜单数组
      cataData: [], // 指标数组
      cataListInterfaceUrl: '',
      filtrateInterfaceUrl: '',
      reportInterfaceUrl: '',
      exportInterfaceUrl: '',
      reportName: '',
      param: {},
      birtParam: {}
    }
  },
  created () {
    const vm = this
    // if(window.$route.query.reportPath) {
    //   vm.cataId = window.$route.query.reportPath
    //   console.log('传过来的cataId: ' + vm.cataId)
    // }
    vm.initApiUrl()
    const url = location.search // 获取url中"?"符后的字串 ('?modFlag=business&role=1')
    // console.log( 'url: ' + url )
    const theRequest = new Object()
    if (url.indexOf('?') != -1) {
      const str = url.substr(1) // substr()方法返回从参数值开始到结束的字符串；
      const strs = str.split('&')
      for (let i = 0; i < strs.length; i++) {
        theRequest[strs[i].split('=')[0]] = (strs[i].split('=')[1])
      }
      vm.cataId = theRequest.reportPath // 此时的theRequest就是我们需要的参数；
      // console.log('传过来的cataId: ' + vm.cataId)
      // console.log( 'theRequest: ' + JSON.stringify(theRequest) )
    }
    vm.getCataList(vm.cataId)
    // console.log('传过来的cataId: ' + vm.cataId)
  },
  methods: {
    // 弹窗搜索
    tosearchDia () {
      const vm = this
      if (vm.searchInput !== '') {
        vm.chooseList = vm.chooseList.filter(item => item.label.indexOf(vm.searchInput) !== -1)
      } else {
        vm.chooseList = vm.diolagList
      }
    },
    // 初始化接口地址
    initApiUrl () {
      // console.log('apiBaseUrl: ' + $twApp.gateway)
      this.cataListInterfaceUrl = $twApp.gateway + '/unified-portal/report/list/'
      this.filtrateInterfaceUrl = $twApp.gateway + '/birt-report/parameter/'
      this.reportInterfaceUrl = $twApp.gateway + '/birt-report/render/J123_Z-2019'
      this.exportInterfaceUrl = $twApp.gateway + '/birt-report/export/'
    },
    setStyle () {
      const style = `
        .tw-filterpane {
          background-color: ${this.filterBgColor};
        }
        .tw-tagfilter {
          position: relative;
          display: flex;
          align-items: flex-start;
          height: calc(${this.filterMargin} * 4 + ${this.filterHeight});
          padding: ${this.filterMargin} 0;
          overflow: hidden;
        }
        .tw-tagfilter-label {
          width: 5em;
          line-height: ${this.filterHeight};
          margin: ${this.filterMargin};
          font-weight: 700;
          color: ${this.labelColor};
          text-align: right;
        }
        .tw-tagfilter-tags > .tw-tag {
          font-size: ${this.fontSize};
          vertical-align: top;
        }
        .tw-tagfilter-tags > .tw-ico.xtftoggle {
          position: absolute;
          top: calc(${this.filterMargin} * 2);
          right: 0;
        }
        .tw-tag.xfilter {
          line-height: ${this.filterHeight};
          margin: ${this.filterMargin};
          border-radius: ${this.borderRadius};
        }
        .tw-tag {
          display: inline-block;
          height: 24px;
          line-height: 24px;
          padding: 0 5px;
          color: ${this.color};
          font-style: normal;
          text-align: center;
          border-radius: 2px;
        }
        .tw-tagfilter.xobvious .tw-tag.xfilter {
          color: ${this.color};
          border-color: ${this.borderColor};
          font-size: ${this.fontSize};
        }
        .tw-tagfilter.xobvious .tw-tag.xactive{
          position: relative;
          color: ${this.chooseColor};
          border-color: ${this.chooseBgColor};
        }
        .tw-filterpane.xborder{
          border: 1px solid ${this.filterBorderColor};
        }
        .tw-filterpane.xbg{
          background: ${this.filterBgColor};
        }
        .tw-tag.xfilter:hover {
          color: ${this.chooseColor};
          background: ${this.chooseBgColor};
        }
        .tw-tag.xfilter.xactive {
          color: ${this.chooseColor};
          background: ${this.chooseBgColor};
        }
        .xtftoggle {
          font-size: 24px;
        }
        .tw-ico.xtftoggle:hover {
          color: ${this.chooseBgColor}
        }
        .tw-btn.xmain {
          color: ${this.xmainColor};
          background: ${this.xmainBgColor};
          border-color: ${this.xmainBgColor};
        }
        .tw-btn.xmain:hover {
          background: ${this.xmainFoucsColor}
        }
        .tw-btn.xweaking {
          color: ${this.xweakingColor};
          background: ${this.xweakingBgColor};
          border-color: #ccc;
        }
        .tw-btn.xweaking:hover {
          color: ${this.xweakingFoucsColor};
          background: ${this.xweakingBgColor};
          border-color: ${this.xweakingFoucsColor};
        }
      `
      const styleEl = document.createElement('style')
      styleEl.innerText = style.replace(/\n/g, '')

      document.head.appendChild(styleEl)
    },
    /**
     * 功能: 初始化是否显示切换按钮及选中状态等
     */
    init () {
      this.$nextTick(() => {
        if (this.parameters && this.parameters.length > 0) {
          this.parameters.forEach((item, index) => {
            this.values.push('')
            this.showToggleBtn.push(false)
            if (this.$refs['tag-box'][index].offsetHeight > this.toggleHeight) {
              this.showToggleBtn[index] = true
            }
          })
        }
      })
    },
    // 查询筛选条件
    changeProject (value) {
      const vm = this
      vm.parameters = []
      vm.reportData = ''
      const params = {}
      value = value.substring(0, value.lastIndexOf('.'))
      vm.birtValue = value
      window.axios.post(vm.filtrateInterfaceUrl + value, params).then(resp => {
        let param = []
        param = resp.data
        if (param.length > 1) {
          param[1].items = param[1].items.reverse()
        }
        vm.parameters = param
        for (let i = 0; i < param.length; i++) {
          vm.birtParam[param[i].label] = param[i].items[0].value
          vm.defaultValues.push(param[i].items[0].value)
        }
        this.renderReport()
        vm.values = []
      })
    },

    /**
     * 功能: 点击标签处理
     * @param {Object} tag 标签对应的数据对象
     */
    clickTag (tag, index) {
      this.defaultValues = []
      this.birtParam = {}
      this.values.splice(index, 1, tag.value)
      this.defaultValues[index] = ''
    },

    // 点击查询按钮
    renderReport () {
      // window.axios.defaults.headers.common['Role-Type'] = '3'
      // window.axios.defaults.headers.common['Access-Token'] = '8c5bbc5cbae6909930327010197d67e0'
      // window.axios.defaults.headers.common['Current-Org-Id'] = 'TWPAAS1200000000000'
      // window.axios.defaults.headers.common['Tenant-Id'] = 'CXY0001'
      // window.axios.defaults.headers.common['X-Client-Id'] = 'cb588fd3f6d04cf9bdc0275c4d353e31'
      // window.axios.defaults.headers.common['X-User-Account'] = 'TWPAAS1200000082391'
      const vm = this
      // console.log('vm.birtValue: ' + vm.birtValue)
      vm.reportData = ''
      let param = {}
      // console.log('vm.values: ' + JSON.stringify(vm.values))
      // console.log('vm.parameters: ' + JSON.stringify(vm.parameters))
      // console.log('parameters: ' + JSON.stringify(vm.parameters[0].items[0].label + vm.parameters[1].items[0].value))
      if (Object.keys(vm.birtParam).length > 0) {
        param = vm.birtParam
      } else {
        if (vm.values.length !== vm.parameters.length) {
          console.log('查询失败')
          return
        }
        for (let i = 0; i < vm.parameters.length; i++) {
          param[vm.parameters[i].label] = vm.values[i]
        }
        vm.param = param
        // console.log(
        //   '查询参数:' + JSON.stringify(param) + ' 报表名称：' + vm.reportName
        // )
      }
      window.axios
        .post(vm.reportInterfaceUrl + vm.birtValue, param)
        .then(resp => {
          vm.reportData = resp.data
          // vm.birtParam = {}
        })
    },
    // 点击重置按钮
    renderReset () {
      this.values.splice(0, this.parameters.length, '')
    },
    // 导出EXCEL
    exportExcel () {
      const vm = this
      // console.log('vm.reportName: ' + vm.reportName)
      if (vm.values.length !== vm.parameters.length) {
        console.log('导出EXCEL失败')
        return
      }
      // console.log('vm.param: ' + JSON.stringify(vm.param))
      window.location.href =
        vm.exportInterfaceUrl +
        vm.birtValue +
        '?Access-Token=' + $twApp.user.token +
        '&name=' + vm.reportName +
        '&params=' +
        encodeURIComponent(JSON.stringify(vm.param))
    },
    // 根据报表变化，获取指标列表
    getCataList () {
      // window.axios.defaults.headers.common['Role-Type'] = '3'
      // window.axios.defaults.headers.common['Access-Token'] = '8c5bbc5cbae6909930327010197d67e0'
      // window.axios.defaults.headers.common['Current-Org-Id'] = 'TWPAAS1200000000000'
      // window.axios.defaults.headers.common['Tenant-Id'] = 'CXY0001'
      // window.axios.defaults.headers.common['X-Client-Id'] = 'cb588fd3f6d04cf9bdc0275c4d353e31'
      // window.axios.defaults.headers.common['X-User-Account'] = 'TWPAAS1200000082391'
      const params = {
        condition: { cataId: '', status: '1' },
        pageNo: 1,
        pageSize: 100
      }
      params.condition.cataId = this.cataId
      // params.condition.cataId = 'DEVELOP108160'
      window.axios.post(`${window.$twApp.gateway}/unified-portal/report/parameter/list`, params).then(resp => {
        this.cataData = resp.data.result.list
        // if (this.cataData.length === 1) {
        //   this.chooseCataId(this.cataData[0], 0)
        // }
        this.chooseCataId(this.cataData[0], 0)

        debugger

        this.years = []

        this.$nextTick(() => {
          if (this.$refs['tag-boxs'].offsetHeight > this.toggleHeight) {
            this.showToggleBtns = true
          }
        })
        // console.log('指标列表 ' + JSON.stringify(this.cataData))
      })
    },
    // 选中指标获取筛选列表
    chooseCataId (item, index) {
      // console.log('选中指标获取筛选列表 ' + JSON.stringify(item))
      this.reportName = item.name
      this.chooseReport = item.reportId
      this.changeProject(item.reportPath)
      // console.log('this.reportName: ' + this.reportName)
    }
  },

  computed: {
    style () {
      return {
        cataId: this.cataId,
        cataListInterfaceUrl: this.cataListInterfaceUrl,
        filtrateInterfaceUrl: this.filtrateInterfaceUrl,
        reportInterfaceUrl: this.reportInterfaceUrl,
        exportInterfaceUrl: this.exportInterfaceUrl,
        filterMargin: this.filterMargin,
        filterHeight: this.filterHeight,
        filterBgColor: this.filterBgColor,
        filterBorderColor: this.filterBorderColor,
        labelColor: this.labelColor,
        fontSize: this.fontSize,
        color: this.color,
        borderColor: this.borderColor,
        chooseBgColor: this.chooseBgColor,
        chooseColor: this.chooseColor,
        borderRadius: this.borderRadius,
        labelWidth: this.labelWidth,
        xmainColor: this.xmainColor,
        xweakingColor: this.xweakingColor,
        xmainFoucsColor: this.xmainFoucsColor,
        xweakingFoucsColor: this.xweakingFoucsColor,
        xmainBgColor: this.xmainBgColor,
        xweakingBgColor: this.xweakingBgColor
      }
    }
  },
  mounted () {
    window.axios.defaults.headers = {
      'X-Client-Id': 'cb588fd3f6d04cf9bdc0275c4d353e31',
      'Access-Token': 'cfe4f6c06736a40323638bf879a6d948',
      'Current-Org-Id': 'TWPAAS1200000001964',
      'Tenant-Id': 'BJ00002',
      'X-User-Account': 'TWPAAS1200000082265'
    }

    this.setStyle()
    this.init()
  },

  watch: {
    style: {
      deep: true,
      handler () {
        this.setStyle()
      }
    },
    parameters () {
      this.init()
    },
    cataId (newValue, oldValue) {
      this.getCataList()
      // console.log('newValue: ' + newValue, 'oldValue: ' + oldValue)
    }
  }
}
</script>

<style lang="scss">
@import './css/index.scss';
</style>
